{% extends 'base.html' %}
{% load static %}

{% block title %}购物车 - 商城系统{% endblock %}

{% block extra_css %}
<style>
    .cart-container {
        padding: 20px;
        background-color: #fff;
        border-radius: 8px;
        box-shadow: 0 1px 5px rgba(0,0,0,0.1);
    }
    
    .cart-header {
        padding-bottom: 15px;
        border-bottom: 1px solid #eee;
        margin-bottom: 20px;
    }
    
    .cart-title {
        font-size: 1.5rem;
        font-weight: 600;
        margin-bottom: 0;
    }
    
    .cart-item {
        margin-bottom: 20px;
        padding-bottom: 20px;
        border-bottom: 1px solid #eee;
        will-change: transform, opacity;
        transition: opacity 0.2s;
    }
    
    .cart-item:last-child {
        border-bottom: none;
    }
    
    .cart-item-img {
        width: 100px;
        height: 100px;
        object-fit: contain;
    }
    
    .cart-item-name {
        font-weight: 600;
        margin-bottom: 5px;
    }
    
    .cart-item-price {
        color: #e74c3c;
        font-weight: 600;
    }
    
    .cart-item-original-price {
        color: #95a5a6;
        text-decoration: line-through;
        font-size: 0.9rem;
    }
    
    .quantity-control {
        display: flex;
        align-items: center;
        max-width: 140px;
    }
    
    .quantity-control .btn {
        width: 36px;
        height: 36px;
        font-size: 1rem;
        padding: 0;
        display: flex;
        align-items: center;
        justify-content: center;
    }
    
    .quantity-control input {
        width: 50px;
        height: 36px;
        text-align: center;
        font-size: 1rem;
        border-left: 0;
        border-right: 0;
        border-radius: 0;
    }
    
    .cart-summary {
        padding: 20px;
        background-color: #f8f9fa;
        border-radius: 8px;
    }
    
    .summary-title {
        font-size: 1.2rem;
        font-weight: 600;
        margin-bottom: 15px;
    }
    
    .summary-row {
        display: flex;
        justify-content: space-between;
        margin-bottom: 10px;
    }
    
    .summary-row.total {
        border-top: 1px solid #ddd;
        padding-top: 10px;
        margin-top: 10px;
    }
    
    .total-price {
        color: #e74c3c;
        font-size: 1.5rem;
        font-weight: bold;
    }
    
    .empty-cart {
        text-align: center;
        padding: 40px 20px;
    }
    
    .empty-cart i {
        font-size: 4rem;
        color: #ccc;
        margin-bottom: 20px;
    }
    
    .continue-shopping {
        margin-top: 20px;
    }
    
    /* 添加加载状态的样式 */
    .cart-item.loading {
        opacity: 0.7;
        pointer-events: none;
    }
    
    .btn-remove {
        background: none;
        border: none;
        color: #dc3545;
        cursor: pointer;
        padding: 0;
    }
    
    .btn-remove:hover {
        color: #a71d2a;
    }
    
    /* 图片懒加载样式 */
    .lazy-load {
        opacity: 0;
        transition: opacity 0.3s;
    }
    
    .lazy-load.loaded {
        opacity: 1;
    }
    
    /* 添加内容加载指示器 */
    .cart-loading {
        display: flex;
        justify-content: center;
        align-items: center;
        height: 100px;
    }
    
    .cart-loading .spinner-border {
        width: 3rem;
        height: 3rem;
    }
    
    /* 售罄商品样式 */
    .cart-item.out-of-stock {
        opacity: 0.6;
        background-color: #f9f9f9;
        border-radius: 8px;
        position: relative;
    }
    
    .cart-item.out-of-stock::after {
        content: "已售罄";
        position: absolute;
        top: 50%;
        left: 50%;
        transform: translate(-50%, -50%) rotate(-15deg);
        font-size: 28px;
        color: #dc3545;
        font-weight: bold;
        border: 3px solid #dc3545;
        padding: 5px 15px;
        border-radius: 5px;
        background-color: rgba(255, 255, 255, 0.7);
        z-index: 10;
        pointer-events: none;
    }
    
    .cart-item.out-of-stock .cart-item-img {
        filter: grayscale(100%);
    }
    
    .cart-item.out-of-stock a {
        color: #6c757d !important;
    }
</style>
{% endblock %}

{% block content %}
<div class="container mt-4 mb-5">
    <div class="row">
        <!-- 购物车列表 -->
        <div class="col-lg-8 mb-4">
            <div class="cart-container">
                <div class="cart-header d-flex justify-content-between align-items-center">
                    <h2 class="cart-title">我的购物车</h2>
                    <span class="text-muted cart-count">共 {{ cart_items.count }} 件商品</span>
                </div>
                
                {% if cart_items %}
                <div class="cart-items">
                    {% for item in cart_items %}
                    <div class="cart-item {% if item.product.stock <= 0 %}out-of-stock{% endif %}" data-item-id="{{ item.id }}" data-price="{{ item.product.price }}" data-stock="{{ item.product.stock }}">
                        <div class="row align-items-center">
                            <!-- 选择框 -->
                            <div class="col-auto">
                                <div class="form-check">
                                    <input class="form-check-input item-checkbox" type="checkbox" value="{{ item.id }}" 
                                           id="cartItem{{ item.id }}" 
                                           {% if item.selected and item.product.stock > 0 %}checked{% endif %}
                                           data-item-id="{{ item.id }}"
                                           {% if item.product.stock <= 0 %}disabled{% endif %}>
                                </div>
                            </div>
                            
                            <!-- 商品图片 -->
                            <div class="col-auto">
                                <a href="{% url 'product_detail' item.product.id %}">
                                    <img src="" data-src="{{ item.product.get_main_image_url }}" alt="{{ item.product.name }}" class="cart-item-img lazy-load">
                                </a>
                            </div>
                            
                            <!-- 商品信息 -->
                            <div class="col">
                                <div class="cart-item-info d-flex flex-column flex-grow-1">
                                    <h5 class="mb-1">
                                        <a href="{% url 'product_detail' item.product.id %}" class="text-decoration-none text-dark">{{ item.product.name }}</a>
                                    </h5>
                                    <div class="d-flex justify-content-between align-items-center">
                                        <div class="cart-item-price">
                                            <span class="text-danger fw-bold">¥{{ item.product.price }}</span>
                                        {% if item.product.original_price and item.product.original_price > item.product.price %}
                                            <span class="text-muted text-decoration-line-through ms-2">¥{{ item.product.original_price }}</span>
                                            {% endif %}
                                        </div>
                                        
                                        <!-- 库存信息 -->
                                        <div class="cart-item-stock">
                                            {% if item.product.stock > 0 %}
                                                {% if item.product.stock < 10 %}
                                                <span class="text-warning">库存紧张：{{ item.product.stock }}件</span>
                                                {% endif %}
                                            {% else %}
                                                <span class="badge bg-danger">已售罄</span>
                                            {% endif %}
                                        </div>
                                    </div>
                                </div>
                            </div>
                            
                            <!-- 数量控制 -->
                            <div class="col-auto">
                                <div class="input-group">
                                    <button class="btn btn-outline-secondary decrease-btn" data-item-id="{{ item.id }}" {% if item.product.stock <= 0 %}disabled{% endif %}>-</button>
                                    <input type="text" class="form-control text-center quantity-input" value="{{ item.quantity }}" data-item-id="{{ item.id }}" data-max-stock="{{ item.product.stock }}" {% if item.product.stock <= 0 %}disabled{% endif %}>
                                    <button class="btn btn-outline-secondary increase-btn" data-item-id="{{ item.id }}" {% if item.product.stock <= 0 %}disabled{% endif %}>+</button>
                                </div>
                                {% if item.product.stock > 0 and item.quantity > item.product.stock %}
                                <div class="text-info small mt-1">
                                    <i class="bi bi-info-circle-fill"></i> 当前库存: {{ item.product.stock }}件
                                </div>
                                {% endif %}
                            </div>
                            
                            <!-- 小计 -->
                            <div class="col-auto">
                                <div class="item-subtotal text-right" data-item-id="{{ item.id }}">
                                    <span class="cart-item-price">¥{{ item.total_price }}</span>
                                </div>
                            </div>
                            
                            <!-- 删除按钮 -->
                            <div class="col-auto">
                                <button type="button" class="btn-remove btn-remove-item" data-item-id="{{ item.id }}">
                                    <i class="bi bi-trash"></i>
                                </button>
                            </div>
                        </div>
                    </div>
                    {% endfor %}
                </div>
                {% else %}
                <div class="empty-cart">
                    <i class="bi bi-cart-x"></i>
                    <h3>您的购物车还是空的</h3>
                    <p>快去添加心仪的商品吧！</p>
                    <a href="{% url 'index' %}" class="btn btn-primary continue-shopping">去购物</a>
                </div>
                {% endif %}
            </div>
        </div>
        
        <!-- 订单信息 -->
        <div class="col-lg-4">
            <div class="cart-summary sticky-top" style="top: 20px; z-index: 900;">
                <h3 class="summary-title">订单信息</h3>
                
                <div class="summary-row">
                    <span>商品件数</span>
                    <span id="selected-count" class="selected-count">{{ selected_count|default:0 }} 件</span>
                </div>
                
                <div class="summary-row total">
                    <span>总计</span>
                    <span id="total-price" class="total-price">¥{{ total_price }}</span>
                </div>
                
                <div class="mt-4">
                    <button class="btn btn-danger btn-lg w-100 checkout-btn" id="checkout-btn" {% if not cart_items %}disabled{% endif %}>
                        去结算
                    </button>
                </div>
                
                <div class="mt-3">
                    <a href="{% url 'index' %}" class="btn btn-outline-secondary w-100">
                        继续购物
                    </a>
                </div>
            </div>
        </div>
    </div>
</div>
{% endblock %}

{% block extra_js %}
<script>
    // 页面加载完成后初始化
    document.addEventListener('DOMContentLoaded', function() {
        // 初始化懒加载
        initLazyLoad();
        
        // 初始化购物车交互
        initCartInteractions();
        
        // 更新购物车总计
        updateCartTotal();
        
        // 自动取消已售罄商品的选中状态
        unselectOutOfStockItems();
    });
    
    // 自动取消已售罄商品的选中状态
    function unselectOutOfStockItems() {
        const outOfStockItems = document.querySelectorAll('.cart-item.out-of-stock');
        outOfStockItems.forEach(item => {
            const itemId = item.dataset.itemId;
            const checkbox = document.querySelector(`.item-checkbox[data-item-id="${itemId}"]`);
            
            if (checkbox && checkbox.checked) {
                checkbox.checked = false;
                // 向服务器发送请求，更新选中状态
                updateItemSelection(itemId, false);
            }
        });
    }
    
    // 初始化购物车交互
    function initCartInteractions() {
        // 全选/取消全选功能
        const selectAllCheckbox = document.getElementById('select-all');
        const itemCheckboxes = document.querySelectorAll('.item-checkbox:not([disabled])'); // 排除已禁用的复选框
        
        if (selectAllCheckbox) {
            selectAllCheckbox.addEventListener('change', function() {
                const isChecked = this.checked;
                itemCheckboxes.forEach(function(checkbox) {
                    checkbox.checked = isChecked;
                    updateItemSelection(checkbox.dataset.itemId, isChecked);
                });
            });
        }
        
        // 单个商品选择
        itemCheckboxes.forEach(function(checkbox) {
            checkbox.addEventListener('change', function() {
                updateItemSelection(this.dataset.itemId, this.checked);
                
                // 检查是否所有可选择的商品都被选中
                const allChecked = Array.from(itemCheckboxes).every(cb => cb.checked);
                if (selectAllCheckbox) {
                    selectAllCheckbox.checked = allChecked;
                }
            });
        });
        
        // 去结算按钮点击事件
        const checkoutBtn = document.getElementById('checkout-btn');
        if (checkoutBtn) {
            checkoutBtn.addEventListener('click', function() {
                // 检查是否有选中的商品
                const selectedItems = document.querySelectorAll('.item-checkbox:checked');
                if (selectedItems.length === 0) {
                    alert('请至少选择一件商品进行结算');
                    return;
                }
                
                // 跳转到结算页面
                window.location.href = "{% url 'checkout_redirect' %}";
            });
        }
        
        // 数量增减功能 - 仅对非售罄商品有效
        const decreaseButtons = document.querySelectorAll('.decrease-btn:not([disabled])');  // 减号
        const increaseButtons = document.querySelectorAll('.increase-btn:not([disabled])');  //加号
        const quantityInputs = document.querySelectorAll('.quantity-input:not([disabled])');  // 数量
        
        decreaseButtons.forEach(function(button) {
            button.addEventListener('click', function() {
                const itemId = this.dataset.itemId;
                const input = document.querySelector(`.quantity-input[data-item-id="${itemId}"]`);
                let value = parseInt(input.value);
                if (value > 1) {
                    value--;
                    input.value = value;
                    updateCartItemQuantity(itemId, value);
                }
            });
        });
        
        increaseButtons.forEach(function(button) {
            button.addEventListener('click', function() {
                const itemId = this.dataset.itemId;
                const input = document.querySelector(`.quantity-input[data-item-id="${itemId}"]`);
                let value = parseInt(input.value);
                
                // 增加数量
                value++;
                input.value = value;
                updateCartItemQuantity(itemId, value);
            });
        });
        
        quantityInputs.forEach(function(input) {
            input.addEventListener('change', function() {
                const itemId = this.dataset.itemId;
                let value = parseInt(this.value);
                
                if (isNaN(value) || value < 1) {
                    value = 1;
                }
                
                this.value = value;
                updateCartItemQuantity(itemId, value);
            });
        });
        
        // 更新购物车商品数量
        function updateCartItemQuantity(itemId, quantity) {
            fetch(`/products/cart/update/${itemId}/`, {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                    'X-Requested-With': 'XMLHttpRequest',
                    'X-CSRFToken': getCookie('csrftoken')
                },
                body: JSON.stringify({
                    quantity: quantity
                })
            })
            .then(response => response.json())
            .then(data => {
                if (data.success) {
                    // 更新商品小计
                    const subtotalElement = document.querySelector(`.item-subtotal[data-item-id="${itemId}"]`);
                    if (subtotalElement) {
                        subtotalElement.textContent = `¥${data.item_total}`;
                    }
                    
                    // 更新总计
                    updateCartTotal();
                    
                    // 检查商品是否售罄
                    if (data.current_stock !== undefined && data.current_stock <= 0) {
                        const cartItem = document.querySelector(`.cart-item[data-item-id="${itemId}"]`);
                        if (cartItem) {
                            cartItem.classList.add('out-of-stock');
                            
                            // 禁用相关控件
                            const checkbox = cartItem.querySelector('.item-checkbox');
                            const quantityInput = cartItem.querySelector('.quantity-input');
                            const decreaseBtn = cartItem.querySelector('.decrease-btn');
                            const increaseBtn = cartItem.querySelector('.increase-btn');
                            
                            if (checkbox) {
                                checkbox.checked = false;
                                checkbox.disabled = true;
                                updateItemSelection(itemId, false);
                            }
                            
                            if (quantityInput) quantityInput.disabled = true;
                            if (decreaseBtn) decreaseBtn.disabled = true;
                            if (increaseBtn) increaseBtn.disabled = true;
                            
                            // 添加售罄标签
                            const stockInfo = cartItem.querySelector('.cart-item-stock');
                            if (stockInfo) {
                                stockInfo.innerHTML = '<span class="badge bg-danger">已售罄</span>';
                            }
                        }
                    }
                } else {
                    // 显示错误消息
                    alert(data.message || '更新失败');
                    
                    // 如果返回了调整后的数量，更新输入框
                    if (data.current_quantity) {
                        const input = document.querySelector(`.quantity-input[data-item-id="${itemId}"]`);
                        if (input) {
                            input.value = data.current_quantity;
                        }
                    }
                }
            })
            .catch(error => {
                console.error('Error:', error);
            });
        }
    
        // 移除购物车商品
        document.querySelectorAll('.btn-remove-item').forEach(button => {
            button.addEventListener('click', function() {
                const itemId = this.dataset.itemId;
                if (confirm('确定要从购物车中移除此商品吗？')) {
                    removeCartItem(itemId);
                }
            });
        });
    }
    
    // 更新购物车总计
    function updateCartTotal() {
        const selectedItems = document.querySelectorAll('.item-checkbox:checked');
        let totalPrice = 0;
        let totalCount = 0;
        
        selectedItems.forEach(function(checkbox) {
            const itemId = checkbox.dataset.itemId;
            const cartItem = document.querySelector(`.cart-item[data-item-id="${itemId}"]`);
            const price = parseFloat(cartItem.dataset.price);
            const quantity = parseInt(document.querySelector(`.quantity-input[data-item-id="${itemId}"]`).value);
            
            totalPrice += price * quantity;
            totalCount += quantity;
        });
        
        // 更新总价和选中数量
        document.getElementById('total-price').textContent = '¥' + totalPrice.toFixed(2);
        document.getElementById('selected-count').textContent = totalCount;
        
        // 更新全选状态
        const availableCheckboxes = document.querySelectorAll('.item-checkbox:not([disabled])');
        const allChecked = availableCheckboxes.length > 0 && 
                          Array.from(availableCheckboxes).every(checkbox => checkbox.checked);
        
        const selectAll = document.getElementById('select-all');
        if (selectAll) {
            selectAll.checked = allChecked;
        }
        
        // 更新结算按钮状态
        const checkoutBtn = document.getElementById('checkout-btn');
        if (checkoutBtn) {
            checkoutBtn.disabled = selectedItems.length === 0;
        }
    }
    
    // 切换商品选中状态
    function updateItemSelection(itemId, selected) {
        // 立即在前端更新总计
        updateCartTotal();
        
        // 检查商品是否售罄
        const cartItem = document.querySelector(`.cart-item[data-item-id="${itemId}"]`);
        if (cartItem && cartItem.classList.contains('out-of-stock') && selected) {
            // 不允许选中售罄商品
            const checkbox = document.querySelector(`.item-checkbox[data-item-id="${itemId}"]`);
            if (checkbox) {
                checkbox.checked = false;
            }
            return;
        }
        
        fetch(`/products/cart/toggle-select/${itemId}/`, {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json',
                'X-Requested-With': 'XMLHttpRequest',
                'X-CSRFToken': getCookie('csrftoken')
            },
            body: JSON.stringify({
                selected: selected
            })
        })
        .then(response => response.json())
        .then(data => {
            if (!data.success) {
                console.error('切换选中状态失败：', data.error);
                // 恢复原状态
                document.querySelector(`.item-checkbox[data-item-id="${itemId}"]`).checked = !selected;
                // 重新更新总计
                updateCartTotal();
            }
        })
        .catch(error => {
            console.error('切换选中状态出错:', error);
            // 网络错误时不回滚UI，假设更新成功
        });
    }
    
    // 移除购物车商品
    function removeCartItem(itemId) {
        // 获取购物车项目元素
        const cartItem = document.querySelector(`.cart-item[data-item-id="${itemId}"]`);
        
        // 立即在前端移除元素
        cartItem.style.opacity = '0';
        
        // 更新购物车总计（移除该商品的贡献）
        const checkbox = document.querySelector(`.item-checkbox[data-item-id="${itemId}"]`);
        const isSelected = checkbox && checkbox.checked;
        
        // 如果该商品被选中，需要从总计中减去
        if (isSelected) {
            updateCartTotal();
        }
        
        // 获取当前购物车商品总数
        const currentCount = document.querySelectorAll('.cart-item').length;
        
        // 如果这是最后一个商品，准备刷新页面
        const isLastItem = currentCount <= 1;
        
        // 从DOM中移除元素
        setTimeout(() => {
            cartItem.remove();
            
            // 更新购物车商品数量显示
            if (!isLastItem) {
                document.querySelector('.cart-count').textContent = `共 ${currentCount - 1} 件商品`;
            }
            
            // 如果是最后一个商品，刷新页面显示空购物车
            if (isLastItem) {
                window.location.reload();
            }
        }, 300);
        
        // 异步发送请求到服务器
        fetch(`/products/cart/remove/${itemId}/`, {
            method: 'POST',
            headers: {
                'X-Requested-With': 'XMLHttpRequest',
                'X-CSRFToken': getCookie('csrftoken')
            }
        })
        .then(response => response.json())
        .then(data => {
            if (data.success) {
                // 更新购物车图标数量
                const cartCount = document.getElementById('cart-count');
                if (cartCount) {
                    if (data.cart_count > 0) {
                        cartCount.textContent = data.cart_count;
                    } else {
                        cartCount.textContent = '';
                    }
                }
            } else {
                console.error('移除失败：', data.error);
                // 如果服务器操作失败，不回滚UI，而是刷新页面
                window.location.reload();
            }
        })
        .catch(error => {
            console.error('移除商品出错:', error);
            // 网络错误时不回滚UI，假设更新成功
        });
    }
    
    // 获取CSRF Token
    function getCookie(name) {
        let cookieValue = null;
        if (document.cookie && document.cookie !== '') {
            const cookies = document.cookie.split(';');
            for (let i = 0; i < cookies.length; i++) {
                const cookie = cookies[i].trim();
                if (cookie.substring(0, name.length + 1) === (name + '=')) {
                    cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
                    break;
                }
            }
        }
        return cookieValue;
    }
    
    // 懒加载图片
    function initLazyLoad() {
        const lazyImages = document.querySelectorAll('.lazy-load');
        
        if ('IntersectionObserver' in window) {
            const imageObserver = new IntersectionObserver((entries, observer) => {
                entries.forEach(entry => {
                    if (entry.isIntersecting) {
                        const image = entry.target;
                        image.src = image.dataset.src;
                        image.classList.add('loaded');
                        observer.unobserve(image);
                    }
                });
            });
            
            lazyImages.forEach(image => {
                imageObserver.observe(image);
            });
        } else {
            // 回退方案，简单延迟加载
            setTimeout(() => {
                lazyImages.forEach(image => {
                    image.src = image.dataset.src;
                    image.classList.add('loaded');
                });
            }, 200);
        }
    }
</script>
{% endblock %} 